// subpage/pages/balance/balance.js
const app = getApp();
import service from '../../../utils/request'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseUrl: app.data.url,
    upPrice: 0,
    chargePrice: [
      {
        'price': -1,
        'nick': '补足余额'
      },
      {
        'price': 30,
        'nick': '30'
      },
      {
        'price': 50,
        'nick': '50'
      },
      {
        'price': 100,
        'nick': '100'
      },
      {
        'price': 500,
        'nick': '500'
      },
      {
        'price': -99,
        'nick': '输入金额'
      },
    ],
    currentPrice: '',
    balance: 0,
    freeze: 0,
    low: 0,
    available:0,
    refundTotal: 0,
    nowPrice: 0,
    visible: false,
    applyPrice: '',
    isRefund: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
   
  },
  bindKeyInput: function (e) {
    this.setData({
      applyPrice: e.detail.value
    })
  },
  phoneCall(){
    wx.makePhoneCall({
      phoneNumber: '17381912715' 
    })
  },
  showRefund(){
    wx.navigateTo({
      url: '/subpage/pages/balance/refund',
    })
  }, 
  refundList(){
    wx.navigateTo({
      url: '/subpage/pages/pricelog/refund',
    })
  },
  onClose(){
    this.setData({
      visible: false,
      isRefund: false
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getBalance()
    this.loeGet()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  choosePrice(e) {
    // console.log(e)
    let tar =  e.currentTarget.dataset.price ?  e.currentTarget.dataset.price:e.target.dataset.price 
    this.setData({
      currentPrice: tar
    })
    if(tar =='-99'){
      this.setData({
        visible: true
      })
    }
  },
  editPriceAll(){
    this.setData({
      applyPrice: this.data.nowPrice
    })
  },
  //发起退款
  refund(){
    let that = this
    let price = parseFloat(this.data.applyPrice)
    let now =parseFloat(this.data.nowPrice)
    if(price > now){
      console.log('refund',typeof price,typeof now)
      wx.showToast({
        title: '余额不足',
        icon:'none'
      })
      return false
    }
    if(this.data.applyPrice == ''){
      wx.showToast({
        title: '请输入退款金额',
        icon:'none'
      })
      return false
    }
    if(this.data.applyPrice <= 0){
      wx.showToast({
        title: '退款金额不正确',
        icon:'none'
      })
      return false
    }
    if(this.data.isRefund) return false
    this.setData({
      isRefund: true
    })
    let res =  service("POST", '/wallet/refunded/apply', this.data.applyPrice).then(res => {
      console.log('退款', res)
      if(res.data.code ==0){
        wx.showToast({
          title: res.data.msg,
          icon:'success'
        })
      }else{
        wx.showToast({
          title: res.data.msg,
          icon:'none'
        })
      }
      setTimeout(() => {
        let visible = true
        if (res.data.code == 0) {
          that.getApply()
           visible = false
           that.setData({
            applyPrice: ''
           })
        }
        that.setData({
          isRefund: true,
          visible: visible
        })
      }, 1000);
    })
  },
  //我的余额
   getBalance() {
    let that = this
    let res =  service("GET", '/wallet/money', {}).then(res => {
      // console.log('初始化金额', res)
      let price = Math.ceil(30 - res.data.money.balance)
      console.log('初始化金额', res)
      if (res.data.code == 0) {
        that.setData({
          balance: res.data.money.balance,
          freeze: res.data.money.freeze,
          low: 30,
          upPrice: price
        })
        that.getApply()
      }
      if(res.data.code == 414){
        wx.showToast({
          title: '登录信息过期，请重新登录',
          icon:'none'
        })
        wx.navigateTo({
          url: '/subpage/pages/login/login',
        })
       return
      }
    })
  },
  loeGet() {
    let that = this
    service("GET", "/order/balance/available").then(des => {
      console.log(des)
      if (des.data.code ==0){
        that.setData({
           low: des.data.low,
           available: des.data.available,
         })
      }
    })
  },
  getApply() {
    let that = this
    service("GET", "/wallet/refunded/apply_total").then(des => {
      console.log('getApply', des)
      if (des.data.code ==0){
        let now = (that.data.balance - des.data.page - that.data.freeze).toFixed(2)
        now = now > 0 ? now : 0
        that.setData({
           refundTotal: des.data.page,
           nowPrice: now
         })
      }
    })
  },
  lineCharge(){
    this.setData({
      currentPrice: this.data.applyPrice,
    })
    this.chargePay()
  },
  //充值
  chargePay() {
    let that = this
    console.log('金额', this.data.currentPrice)
   
    if (!!this.data.currentPrice == false) {
      wx.showToast({
        title: '请选择充值金额',
        icon: 'none'
      })
      return
    }
    var price = this.data.currentPrice
    if(this.data.available && this.data.currentPrice=='-1'){
      wx.showToast({
        title: '余额达到最低金额，请选择其他面额',
        icon: 'none',
        duration: 3000
      })
      return
    }
    if(this.data.currentPrice === -1) {
      price = Math.ceil(this.data.low - this.data.balance)
    }
    let postData = {
      price: price,
      lng: wx.getStorageSync('lng')?  wx.getStorageSync('lng'): '104.67',
      lat: wx.getStorageSync('lat') ? wx.getStorageSync('lat'): '35.76'
    }
    let res =  service('POST', '/charge/create', postData).then(res => {
      console.log('创建订单', res)
      if (res.data.code == 0) {
        that.weiPay(JSON.parse(res.data.params))
        that.setData({
          visible: false
        })
      } else {
        wx.showToast({
          title: '充值失败，请联系管理员',
          icon: 'none'
        })
      }
    })
    },
  //发起支付
  weiPay(data) {
    let that= this
    wx.requestPayment({
      timeStamp: data.timeStamp,
      nonceStr: data.nonceStr,
      package: data.package,
      signType: data.signType,
      paySign: data.paySign,
      success(res) {
        console.log('用户支付成功', res)
        that.getBalance()
        that.loeGet()
      },
      fail(result) {
        console.log('用户取消了支付', result)
      }
    })
  },
  goLog() {
    wx.navigateTo({
      url: '/subpage/pages/pricelog/pricelog',
    })
  }
})